package com.wuzhun.wxmp.util;

import org.apache.commons.codec.digest.DigestUtils;

import java.security.SecureRandom;
import java.util.Random;
import java.util.UUID;

/**
 *
 * 字符串工具类
 * @author renbaolin
 * @date 2022-12-05 10:20 AM
 */
public class StringUtil {

    /**
     * md5密码
     *
     * @param password
     * @param salt
     * @return
     */
    public static String getMd5Password(String password, String salt) {
        password = password + salt;
        return md5String(password);
    }

    /**
     * 字符串加密
     *
     * @param str
     * @return
     */
    public static String md5String(String str) {
        return DigestUtils.md5Hex(str.getBytes());
    }

    /**
     * 生成Token
     * @param uid
     *
     * @return
     */
    public static String generateToken(Integer uid){
        return md5String(uid + UUID.randomUUID().toString().replaceAll("-",""));
    }

    /**
     * 随机生成字符串
     *
     * @param length
     * @return
     */
    public static String getRandomString(int length) {
        StringBuilder val = new StringBuilder();
        SecureRandom random = new SecureRandom();

        // 参数length，表示生成几位随机数
        for (int i = 0; i < length; i++) {

            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            // 输出字母还是数字
            if ("char".equalsIgnoreCase(charOrNum)) {
                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val.append((char) (random.nextInt(26) + temp));
            } else {
                val.append(random.nextInt(10));
            }
        }
        return val.toString();
    }

}
